<?php

namespace app\admin\controller;

use addons\third\library\Application;
use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use app\admin\model\SstalinkDevice;
use app\common\controller\Backend;
use app\common\library\Email;
use think\Validate;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login','register','check','geetest','startcaptchaservlet','viewall','viewsensors',''];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    private $salt_data='bc4b2a76b9719d91';

    public function _initialize()
    {
        parent::_initialize();
        $this->device_model = model('SstalinkDevice');
        $this->sensor_model = model('SstalinkSensor');
    }

    /**
     * 后台首页
     */
    public function index()
    {
        //
        $menulist = $this->auth->getSidebar([
            'dashboard'  => 'hot',
            'addon'       => ['new', 'red', 'badge'],
            'auth/rule'  => 'side',
            //'general'    => ['18', 'purple'],
                ], $this->view->site['fixedpage']);
        $this->view->assign('menulist', $menulist);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    public function viewall(){
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->device_model
                ->order($sort, $order)
                ->count();
            $list = $this->device_model
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }else {
            return $this->fetch();
        }
    }

    public function viewsensors($ids){
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->sensor_model
                ->where('deviceid','=',$ids)
                ->order($sort, $order)
                ->count();
            $list = $this->sensor_model
                ->where('deviceid','=',$ids)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }else {
            return $this->fetch();
        }
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin())
        {
            $this->error(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule);
            $result = $validate->check($data);
            if (!$result)
            {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            \app\admin\model\AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true)
            {
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            }
            else
            {
                $this->error(__('Username or password is incorrect'), $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin())
        {
            $this->redirect($url);
        }
        $background = cdnurl("/assets/img/loginbg.jpg");
        $this->view->assign('background', $background);
        \think\Hook::listen("login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'), 'index/login');
    }

    /**
     * 注册
     * @return mixed|\think\response\Json
     */
    public function register(){
        global $salt_data;
        $url = "http://link.hdussta.cn/admin/index";
        if ($this->auth->isLogin())
        {
            $this->error(__("你以登录"), $url);
        }
        if($this->request->isPost() || $this->request->isAjax()){
            $username=$this->request->post("username");
            $password=$this->request->post("password");
            $email=$this->request->post("email");
            $rule = [
                'username'  => 'require|length:3,30|alphaDash',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
            ];
            $data=[
                'username'  =>  $username,
                'password'  =>  $password,
                'email'     =>  $email,
            ];
            $validate=new Validate($rule);
            $result=$validate->check($data);
            if(!$this->geetest()){
                return json(['status' => -1,'info' => '验证失败,请刷新页面后重试']);
            }
            if(!$result){
                json(['status' => -1,'info' => '输入不符合规范']);
            }
            $v_admin=Admin::get(['username' =>  $username]);
            if($v_admin){
                return json(['status' => -1,'info' => '用户已注册']);
            }
            $v_email=Admin::get(['email' => $email]);
            if($v_email){
                return json(['status' => -1,'info' => '邮箱已注册']);
            }
            $salt=mb_substr(md5($username.$salt_data),0,6);
            $b=md5(md5($password).$salt);
            $a=md5($username.$email.$b.$salt_data);
            $check_url=$this->request->get('url','index/check?username='.$username.'&email='.$email.'&a='.$a.'&b='.$b);
            $result_email=$this->sendMail($email,"注册邮件","http://link.hdussta.cn/admin/".$check_url);
            if($result_email){
                return json(['status' => 1,'info' => '注册邮件已发送']);
            }else{
                return json(['status' => -1,'info' => '邮件发送失败，请检查地址是否正确']);
            }
        }else{
            return $this->fetch();
        }
    }

    /**
     * 注册邮件验证
     * @param string $username
     * @param string $email
     * @param string $a
     * @param string $b
     */
    public function check($username="",$email="",$a="",$b=""){
        global $salt_data;
        $url=$this->request->get('url','index/login');
        $data=[
            'username'  =>  $username,
            'email'     =>  $email,
            'a'         =>  $a,
            'b'         =>  $b,
        ];
        $rule=[
            'username'  =>  'require|length:3,30|alphaDash',
            'email'     =>  'require|email',
            'a'         =>  'require|length:32',
            'b'         =>  'require|length:32',
        ];
        $validate=new Validate($rule);
        $result=$validate->check($data);
        if(!$result){
            $this->error("错误的地址",'index/register');
        }else{
            $v_admin=Admin::get(['username' =>  $username]);
            if($v_admin){
                $this->error("用户已注册",'index/register');
            }
            $result=md5($username.$email.$b.$salt_data);
            if($a!=$result){
                $this->error("注册地址验证失败,请重新注册",'index/register');
            }else{
                $admin=[
                    'username'  =>  $username,
                    'nickname'  =>  $username,
                    'password'  =>  $b,
                    'salt'      =>  mb_substr(md5($username.$salt_data),0,6),
                    'avatar'    =>  '/assets/img/avatar.png',
                    'email'     =>  $email,
                    'status'    =>  'normal',
                ];
                if($result=Admin::create($admin)){
                    $admin=Admin::get(['username'   =>  $username]);
                    if($admin){
                        $id=$admin->id;
                        $auth=[
                            'uid'       =>  $id,
                            'group_id'  =>  2,
                        ];
                        if(!AuthGroupAccess::create($auth)){
                            $this->error("未知的错误",'index/register');
                        }
                    }else{
                        $this->error("未知的错误",'index/register');
                    }
                   $this->success("注册成功",'index/login');
                }else{
                    $this->error("未知的错误",'index/register');
                }
            }
        }
    }

    /**
     * 找回密码
     */
    public function findpassword(){
        if($this->request->isPost()){
            $username=$this->request->post('username');
            $email=$this->request->post('email');
            $data=[
                'uesrname'  =>  $username,
                'email'     =>  $email,
            ];
            $rule=[
                'username'  =>  'require|length:3,30|alphaDash',
                'email'     =>  'require|email',
            ];
            $validate=new Validate($rule);
            $result=$validate->check($data);
            if(!$this->geetest()){
                return json(['status' => -1,'info' => '验证失败']);
            }
            if($result){
                $v_user=Admin::get(['username' => $username]);
                if($v_user){
                    if($v_user->email!=$email){
                        return json(['status' => -1,'info' => '邮箱地址错误']);
                    }
                    $n_password=mb_substr(md5(time()),0,8);
                    $result_email=$this->sendMail($email,"找回密码",'<div style=\"min-height:550px; padding: 100px 55px 200px;\">新密码:'.$n_password.' 请尽快登录并修改密码</div>');
                    if($result_email){
                        $v_user->password=md5(md5($n_password).$v_user->salt);
                        $v_user->save();
                        return json(['status' => 1,'info' => '邮件已发送']);
                    }else{
                        return json(['status' => -1,'info' => '邮件发送失败，请联系管理员' ]);
                    }
                }else{
                    return json(['status' => -1,'info' => '用户不存在']);
                }
            }else{
                return json(['status' => -1,'info' => '输入不符合规范']);
            }
        }
        else{
            return $this->fetch();
        }
    }

    /**
     * geetest验证码
     * @return bool
     */
    public function geetest(){
        require_once dirname(dirname(__FILE__)) . '/lib/class.geetestlib.php';
        require_once dirname(dirname(__FILE__)) . '/config/config.php';

        $GtSdk = new \GeetestLib(CAPTCHA_ID, PRIVATE_KEY);
        $data = array(
            "user_id" => $_SESSION['user_id'], # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => $this->request->ip() # 请在此处传输用户请求验证时所携带的IP
        );
        if ($_SESSION['gtserver'] == 1) {   //服务器正常
            $result = $GtSdk->success_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'], $data);
            if ($result) {
                return true;
            } else{
                return false;
            }
        }else{  //服务器宕机,走failback模式
            if ($GtSdk->fail_validate($_POST['geetest_challenge'],$_POST['geetest_validate'],$_POST['geetest_seccode'])) {
                return true;
            }else{
                return false;
            }
        }
    }

    /**
     * geetest验证码
     */
    public function StartCaptchaServlet(){
        require_once dirname(dirname(__FILE__)) . '/lib/class.geetestlib.php';
        require_once dirname(dirname(__FILE__)) . '/config/config.php';
        $GtSdk = new \GeetestLib(CAPTCHA_ID, PRIVATE_KEY);

        $data = array(
            "user_id" => sha1("test"), # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => $this->request->ip() # 请在此处传输用户请求验证时所携带的IP
        );

        $status = $GtSdk->pre_process($data, 1);
        $_SESSION['gtserver'] = $status;
        $_SESSION['user_id'] = $data['user_id'];
        echo $GtSdk->get_response_str();
    }

    function sendMail($receiver,$title,$data){
        $mail=new \PHPMailer();
        //是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
        //$mail->SMTPDebug = 1;

        //使用smtp鉴权方式发送邮件
        $mail->isSMTP();

        //smtp需要鉴权 这个必须是true
        $mail->SMTPAuth=true;

        //链接qq域名邮箱的服务器地址
        $mail->Host = 'smtp.qq.com';

        //设置使用ssl加密方式登录鉴权
        $mail->SMTPSecure = 'ssl';

        //设置ssl连接smtp服务器的远程服务器端口号，以前的默认是25，但是现在新的好像已经不可用了 可选465或587
        $mail->Port = 465;

        //设置smtp的helo消息头 这个可有可无 内容任意
        // $mail->Helo = 'Hello smtp.qq.com Server';

        //设置发件人的主机域 可有可无 默认为localhost 内容任意，建议使用你的域名
        $mail->Hostname = 'http://link.hdussta.cn';

        //设置发送的邮件的编码 可选GB2312 我喜欢utf-8 据说utf8在某些客户端收信下会乱码
        $mail->CharSet = 'UTF-8';

        //设置发件人姓名（昵称） 任意内容，显示在收件人邮件的发件人邮箱地址前的发件人姓名
        $mail->FromName = 'HDUSSTA';

        //smtp登录的账号 这里填入字符串格式的qq号即可
        $mail->Username ='admin@hdussta.cn';

        //smtp登录的密码 使用生成的授权码（就刚才叫你保存的最新的授权码）
        $mail->Password = 'ukdzpapobfcebeda';

        //设置发件人邮箱地址 这里填入上述提到的“发件人邮箱”
        $mail->From = 'admin@hdussta.cn';

        //邮件正文是否为html编码 注意此处是一个方法 不再是属性 true或false
        $mail->isHTML(true);

        //设置收件人邮箱地址 该方法有两个参数 第一个参数为收件人邮箱地址 第二参数为给该地址设置的昵称 不同的邮箱系统会自动进行处理变动 这里第二个参数的意义不大
        $mail->addAddress($receiver);

        //添加多个收件人 则多次调用方法即可
        // $mail->addAddress('xxx@163.com','lsgo在线通知');

        //添加该邮件的主题
        $mail->Subject = $title;

        //添加邮件正文 上方将isHTML设置成了true，则可以是完整的html字符串 如：使用file_get_contents函数读取本地的html文件
        $mail->Body = $data;

        //为该邮件添加附件 该方法也有两个参数 第一个参数为附件存放的目录（相对目录、或绝对目录均可） 第二参数为在邮件附件中该附件的名称
        // $mail->addAttachment('./d.jpg','mm.jpg');
        //同样该方法可以多次调用 上传多个附件
        // $mail->addAttachment('./Jlib-1.1.0.js','Jlib.js');

        $status = $mail->send();
        return $status;

    }


}
